<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入文章标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" style="width: 308px">
        <el-date-picker
            v-model="daterangePublishTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="文章类型" prop="type" style="width: 200px;">
        <el-select v-model="queryParams.type" placeholder="请选择文章类型" clearable>
          <el-option
              v-for="dict in article_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章状态" prop="status" style="width: 200px;">
        <el-select v-model="queryParams.status" placeholder="请选择文章状态" clearable>
          <el-option
              v-for="dict in article_statuses"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="观看量" prop="viewCount">
        <el-input
            v-model="queryParams.viewCount"
            placeholder="请输入观看量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点赞量" prop="likeCount">
        <el-input
            v-model="queryParams.likeCount"
            placeholder="请输入点赞量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收藏量" prop="collectCount">
        <el-input
            v-model="queryParams.collectCount"
            placeholder="请输入收藏量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articlesList" @selection-change="handleSelectionChange">
      <el-table-column label="主键" align="center" prop="articleId"/>
      <el-table-column label="文章标题" align="center" prop="title"/>
      <el-table-column label="文章封面" align="center" prop="coverImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="文章描述" align="center" prop="description"/>
      <!--<el-table-column label="文章内容" align="center" prop="content"/>-->
      <el-table-column label="是否发布" align="center" prop="isPublish">
        <template #default="scope">
          <el-switch
              v-model="scope.row.isPublish"
              active-text="发布"
              inactive-text="未发布"
              active-value="1"
              inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="发布者" align="center" prop="publishBy"/>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文章状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="article_statuses" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改文章管理对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="articlesRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="不通过原因" v-if="form.rejectReason">
          <el-input v-model="form.rejectReason" disabled/>
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio-button
                v-for="dict in article_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题"/>
        </el-form-item>
        <el-form-item label="文章封面">
          <image-upload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="文章描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入文章描述"/>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Articles">
import {
  listArticles,
  getArticles,
  delArticles,
  addArticles,
  updateArticles,
  changePublishStatus
} from "@/api/articles/articles";
import {ref} from "vue";
import {parseTime} from "@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();
const {article_statuses, article_type} = proxy.useDict('article_statuses', 'article_type');

const articlesList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangePublishTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    description: null,
    publishTime: null,
    publishBy: null,
    status: null,
    viewCount: null,
    likeCount: null,
    collectCount: null,
  },
  rules: {
    title: [
      {required: true, message: "文章标题不能为空", trigger: "blur"}
    ],
    description: [
      {required: true, message: "文章描述不能为空", trigger: "blur"}
    ],
    content: [
      {required: true, message: "文章内容不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "文章类型不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

// 修改发布状态
function handleStatusChange(row) {
  // 排除初始化阶段的触发
  if (!row._initialized || isInitialLoad) return;

  let text = row.isPublish === "1" ? "发布" : "下架";
  proxy.$modal.confirm(`确认要${text}文章 "${row.title}" 吗？`)
      .then(() => changePublishStatus(row.articleId, row.isPublish))
      .then(() => {
        proxy.$modal.msgSuccess(`${text}成功`);
        getList();
      })
      .catch(() => {
        row.isPublish = row.isPublish === "0" ? "1" : "0";
      });
}

let isInitialLoad = true; // 新增初始化标记
/** 查询文章管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangePublishTime && '' != daterangePublishTime) {
    queryParams.value.params["beginPublishTime"] = daterangePublishTime.value[0];
    queryParams.value.params["endPublishTime"] = daterangePublishTime.value[1];
  }
  listArticles(queryParams.value).then(response => {
    articlesList.value = response.rows.map(item => ({
      ...item,
      // 添加初始化标记字段
      _initialized: false
    }));

    // 延迟设置开关状态
    setTimeout(() => {
      articlesList.value.forEach(item => {
        item.isPublish = item.isPublish; // 触发响应式更新
        item._initialized = true; // 标记完成初始化
      });
    }, 100);
    // articlesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    isInitialLoad = false; // 关闭初始化标记
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    articleId: null,
    title: null,
    coverImage: null,
    description: null,
    content: null,
    publishTime: null,
    publishBy: null,
    rejectReason: null,
    status: null,
    viewCount: null,
    likeCount: null,
    collectCount: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    delFlag: null
  };
  proxy.resetForm("articlesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangePublishTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.articleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文章管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _articleId = row.articleId || ids.value
  getArticles(_articleId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文章管理";
  });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["articlesRef"].validate(valid => {
    if (valid) {
      if (form.value.articleId != null) {
        updateArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArticles(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _articleIds = row.articleId || ids.value;
  proxy.$modal.confirm('是否确认删除文章管理编号为"' + _articleIds + '"的数据项？').then(function () {
    return delArticles(_articleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

onMounted(() => {
  getList();
})

</script>
